package com.it.reggie.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.reggie.Service.CategoryService;
import com.it.reggie.common.R;
import com.it.reggie.entity.Category;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类方法
     * @param category
     * @return
     */
    @PostMapping
    public R<String> newClassification(@RequestBody Category category){
        log.info("category{}",category);
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param
     * @return
     */

    @GetMapping("/page")
    public R<Page> Paging (int page, int pageSize){
        log.info("参数 page {} pageSize {} name {}",page,pageSize);
        //构造分页构造器
        Page<Category> pageInfo = new Page(page,pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper();

        //排序条件 根据sort进行排序
        lambdaQueryWrapper.orderByAsc(Category::getSort);

        //执行查询
        categoryService.page(pageInfo, lambdaQueryWrapper);
        //返回总条数
        pageInfo.setTotal(categoryService.selectTotalCount());
        return R.success(pageInfo);
    }

    //http://127.0.0.1:8080/category?ids=1621962540517007362
    @DeleteMapping()
    public R<String> deleteById(Long ids){

//        categoryService.removeById(ids);
        categoryService.remove(ids);

        return R.success("分类信息删除成功");
    }

    /**
     * 根据id修改信息
     * @param category
     * @return
     */
    @PutMapping
    public R<String> Update(@RequestBody Category  category){
        log.info("修改分类信息 {}",category);
        categoryService.updateById(category);
        return R.success("修改分类信息成功");
    }

    // 返回
    @GetMapping("/list")
    public R<List<Category>> listType(Integer type){

        if (type!=null) {
            List<Category> categories = categoryService.listText(type);
            return R.success(categories);
        }

        List<Category> categories = categoryService.listAll();
        return R.success(categories);
    }



}
